#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>
#include <QListView>
#include <QList>
#include "LightBulbItem.h"
#include "PowerSourceItem.h"
#include "SwitchItem.h"
#include "PowerSourceWidget.h"
#include "LightBulbWidget.h"
#include "SwitchWidget.h"
#include "CircuitSystem.h"
#include "MyGraphicsScene.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 初始化拖拽信息
    draggingItemType = "";  // 当前拖动的元件类型
    //draggedItem = nullptr;  // 当前拖动的图标（用于显示拖动效果）

    // 创建 QGraphicsScene
    scene = new MyGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    // 设置固定场景范围
    scene->setSceneRect(0, 0, 1000, 1000);  // 设置场景大小为 200x400
    PowerSource = new PowerSourceWidget(this);
    PowerSource->setObjectName("PowerSource");

    LightBulb = new LightBulbWidget(this);
    LightBulb->setObjectName("LightBulb");

    Switch = new SwitchWidget(this);
    Switch->setObjectName("Switch");

    ui->verticalLayout->addWidget(PowerSource);
    ui->verticalLayout->addWidget(LightBulb);
    ui->verticalLayout->addWidget(Switch);

    ui->graphicsView->setStyleSheet("background: transparent;");

    // 获取场景的最左上角位置
    QPointF sceneTopLeft = scene->sceneRect().topLeft();
    // 将视图的焦点设置在场景的最左上角，确保视图不移动
    ui->graphicsView->ensureVisible(sceneTopLeft.x(), sceneTopLeft.y(), 0, 0);

    cs=new CircuitSystem(scene);

    connect(scene, &MyGraphicsScene::emitComponentInfo, this, [this](QString Itemtype, qreal rotation, qreal posX, qreal posY,QString LabelString) {
        // 更新对应的界面元素
        ui->label_3->setText(Itemtype);  // 设置组件类型
        ui->lineEdit->setText(QString::number(rotation));  // 设置旋转角度
        ui->lineEdit_2->setText(QString::number(posX));  // 设置 X 坐标
        ui->lineEdit_3->setText(QString::number(posY));  // 设置 Y 坐标
        ui->label_2->setText(LabelString);

        // 获取场景中选中的组件
        QList<QGraphicsItem*> selectedItems = this->scene->selectedItems();
        if (!selectedItems.isEmpty()) {
            QGraphicsItem* selectedItem = selectedItems.first();  // 获取第一个选中的组件
            qDebug() << "选中组件: " << selectedItem;
            // 临时阻断所有 comboBox 的信号，防止内部设置时触发 currentIndexChanged
            QSignalBlocker blocker1(ui->comboBox);
            QSignalBlocker blocker2(ui->comboBox_2);
            QSignalBlocker blocker3(ui->comboBox_3);
            QSignalBlocker blocker4(ui->comboBox_4);
            QSignalBlocker blocker5(ui->comboBox_5);
            QSignalBlocker blocker6(ui->comboBox_6);
            cs->checkSwitchConnections(selectedItem,ui->comboBox,ui->comboBox_2,ui->comboBox_3,ui->comboBox_4,ui->comboBox_5,ui->comboBox_6);
        } else {
            qDebug() << "没有选中任何组件";
        }

        // 根据组件类型判断，显示或隐藏控件
        if (Itemtype == "SwitchItem") {
            // 如果选中的是 SwitchItem，显示 horizontalLayout_3 和 formLayout 中的所有控件
            for (int i = 0; i < ui->horizontalLayout_3->count(); ++i) {
                QWidget *widget = ui->horizontalLayout_3->itemAt(i)->widget();
                if (widget) widget->show();
            }

            for (int i = 0; i < ui->formLayout->count(); ++i) {
                QWidget *widget = ui->formLayout->itemAt(i)->widget();
                if (widget) widget->show();
            }
        } else {
            // 如果选中的不是 SwitchItem，隐藏 horizontalLayout_3 和 formLayout 中的所有控件
            for (int i = 0; i < ui->horizontalLayout_3->count(); ++i) {
                QWidget *widget = ui->horizontalLayout_3->itemAt(i)->widget();
                if (widget) widget->hide();
            }

            for (int i = 0; i < ui->formLayout->count(); ++i) {
                QWidget *widget = ui->formLayout->itemAt(i)->widget();
                if (widget) widget->hide();
            }
        }
    });
    connect(ui->pushButton_5, &QPushButton::clicked, this, [this]() {
        qDebug() << "点击按钮";

        // 获取场景中选中的组件
        QList<QGraphicsItem*> selectedItems = this->scene->selectedItems();

        if (!selectedItems.isEmpty()) {
            QGraphicsItem* selectedItem = selectedItems.first();  // 获取第一个选中的组件
            qDebug() << "选中组件: " << selectedItem;

            this->cs->removeComponent(selectedItem);  // 调用 CircuitSystem 的 removeComponent 函数来删除组件
        } else {
            qDebug() << "没有选中任何组件";
        }
    });
    // 连接信号和槽
    connect(ui->lineEdit, &QLineEdit::textChanged, this, [this]() {
        bool ok;
        double rotation = ui->lineEdit->text().toDouble(&ok);  // 获取旋转角度（假设是数字）
        if (ok) {
            scene->now_Component()->setRotation(rotation);  // 设置旋转角度
        }
    });

    connect(ui->lineEdit_2, &QLineEdit::textChanged, this, [this]() {
        bool ok;
        double x = ui->lineEdit_2->text().toDouble(&ok);  // 获取 X 坐标值
        if (ok) {
            scene->now_Component()->setX(x);  // 设置 X 坐标
        }
    });

    connect(ui->lineEdit_3, &QLineEdit::textChanged, this, [this]() {
        bool ok;
        double y = ui->lineEdit_3->text().toDouble(&ok);  // 获取 Y 坐标值
        if (ok) {
            scene->now_Component()->setY(y);  // 设置 Y 坐标
        }
    });
    connect(ui->pushButton_3,&QPushButton::clicked,this,[this](){
        // 获取场景中选中的组件
        QList<QGraphicsItem*> selectedItems = this->scene->selectedItems();

        if (!selectedItems.isEmpty()) {
            QGraphicsItem* selectedItem = selectedItems.first();  // 获取第一个选中的组件
            qDebug() << "选中组件: " << selectedItem;
            dynamic_cast<SwitchItem*>(selectedItem)->setLight(false);
            scene->update();
            cs->ElectricCurrent();
            update();
        } else {
            qDebug() << "没有选中任何组件";
        }
    });
    connect(ui->pushButton_4,&QPushButton::clicked,this,[this](){
        // 获取场景中选中的组件
        QList<QGraphicsItem*> selectedItems = this->scene->selectedItems();

        if (!selectedItems.isEmpty()) {
            QGraphicsItem* selectedItem = selectedItems.first();  // 获取第一个选中的组件
            qDebug() << "选中组件: " << selectedItem;
            dynamic_cast<SwitchItem*>(selectedItem)->setLight(true);
            scene->update();
            cs->ElectricCurrent();
            update();
        } else {
            qDebug() << "没有选中任何组件";
        }
    });

    // comboBox（例如主控件，下拉框内容类似 "Lamp"、"Lamp 1端"、"Lamp 2端"）
    // 表示当前选中组件连接时所用参数：包含"1端"则 thickness=1，包含"2端"则 thickness=3，否则 thickness=2
    connect(ui->comboBox, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                // 获取场景中当前选中的组件（假设只选中一个）
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                // 获取下拉框原始文本
                QString comboText = ui->comboBox->currentText();
                // 复制一份用于标签匹配，移除“1端”、“2端”
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                // 遍历场景中所有组件，查找标签与 baseText 匹配的目标组件
                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                // 根据原始 comboText 判断端口信息确定 thickness 参数
                int thickness = 2;
                if (comboText.contains("1端"))
                    thickness = 1;
                else if (comboText.contains("2端"))
                    thickness = 3;

                if (targetItem) {
                    // 如果下拉框中有选项（文本不为空），先断开原有连接
                    if (!ui->comboBox->currentText().isEmpty())
                        cs->deleteConnectionLine(selectedItem, targetItem, scene);

                    // 建立新的连接
                    cs->connectComponents(selectedItem, targetItem, scene, thickness);
                } else {
                    qDebug() << "未找到目标组件";
                }
                update();
            });

    // comboBox_2：代表当前组件的1端连接目标组件
    // 下拉框文本类似 "Lamp 1端"、"Lamp 2端" 或 "Lamp"
    // 如果文本中包含"1端"则 thickness=1，包含"2端"则 thickness=3，否则 thickness=2
    connect(ui->comboBox_2, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                // 获取当前选中的组件
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                // 获取下拉框文本
                QString comboText = ui->comboBox_2->currentText();
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                // 确定 thickness 参数（1端：1，2端：3，默认：2）
                int thickness = 2;
                if (comboText.contains("1端"))
                    thickness = 1;
                else if (comboText.contains("2端"))
                    thickness = 3;

                // 查找目标组件（标签与 baseText 匹配）
                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                if (!targetItem) {
                    qDebug() << "未找到匹配的目标组件";
                    return;
                }

                // 先断开原有连接（如果下拉框文本不为空）
                if (!ui->comboBox_2->currentText().isEmpty())
                    cs->deleteConnectionLine(selectedItem, targetItem, scene);

                // 建立连接（当前组件的1端连接目标组件）
                cs->connectComponents(selectedItem, targetItem, scene, thickness);
                update();
            });


    // comboBox_3：逻辑与 comboBox_2 类似（均表示当前组件的1端），可以单独设置不同的 thickness 映射，如有需要
    connect(ui->comboBox_3, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                QString comboText = ui->comboBox_3->currentText();
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                int thickness = 2;
                if (comboText.contains("1端"))
                    thickness = 1;
                else if (comboText.contains("2端"))
                    thickness = 3;

                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                if (!targetItem) {
                    qDebug() << "未找到匹配的目标组件";
                    return;
                }

                if (!ui->comboBox_3->currentText().isEmpty())
                    cs->deleteConnectionLine(selectedItem, targetItem, scene);

                cs->connectComponents(selectedItem, targetItem, scene, thickness);
                update();
            });


    // comboBox_4：代表当前组件的2端连接目标组件
    // 此处映射：如果文本包含"1端"，则 thickness=4；包含"2端"则 thickness=6；否则 thickness=5
    connect(ui->comboBox_4, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                QString comboText = ui->comboBox_4->currentText();
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                int thickness = 5;
                if (comboText.contains("1端"))
                    thickness = 4;
                else if (comboText.contains("2端"))
                    thickness = 6;

                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                if (!targetItem) {
                    qDebug() << "未找到匹配的目标组件";
                    return;
                }

                if (!ui->comboBox_4->currentText().isEmpty())
                    cs->deleteConnectionLine(selectedItem, targetItem, scene);

                cs->connectComponents(selectedItem, targetItem, scene, thickness);
                update();
            });


    // comboBox_5：同 comboBox_4，映射关系相同（或根据需要调整）
    connect(ui->comboBox_5, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                QString comboText = ui->comboBox_5->currentText();
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                int thickness = 5;
                if (comboText.contains("1端"))
                    thickness = 4;
                else if (comboText.contains("2端"))
                    thickness = 6;

                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                if (!targetItem) {
                    qDebug() << "未找到匹配的目标组件";
                    return;
                }

                if (!ui->comboBox_5->currentText().isEmpty())
                    cs->deleteConnectionLine(selectedItem, targetItem, scene);

                cs->connectComponents(selectedItem, targetItem, scene, thickness);
                update();
            });


    // comboBox_6：同上
    connect(ui->comboBox_6, &QComboBox::currentIndexChanged, this,
            [this](int index) {
                QList<QGraphicsItem*> selectedItems = scene->selectedItems();
                if (selectedItems.isEmpty()) {
                    qDebug() << "没有选中任何组件";
                    return;
                }
                QGraphicsItem* selectedItem = selectedItems.first();

                QString comboText = ui->comboBox_6->currentText();
                QString baseText = comboText;
                if (baseText.contains("端")) {
                    baseText.remove("1端");
                    baseText.remove("2端");
                    baseText = baseText.trimmed();
                }

                int thickness = 5;
                if (comboText.contains("1端"))
                    thickness = 4;
                else if (comboText.contains("2端"))
                    thickness = 6;

                QGraphicsItem* targetItem = nullptr;
                QList<QGraphicsItem*> allItems = scene->items();
                for (QGraphicsItem* item : allItems) {
                    QString label;
                    if (auto light = dynamic_cast<LightBulbItem*>(item))
                        label = light->getLabel();
                    else if (auto power = dynamic_cast<PowerSourceItem*>(item))
                        label = power->getLabel();
                    else if (auto sw = dynamic_cast<SwitchItem*>(item))
                        label = sw->getLabel();
                    else
                        continue;

                    if (label == baseText) {
                        targetItem = item;
                        break;
                    }
                }

                if (!targetItem) {
                    qDebug() << "未找到匹配的目标组件";
                    return;
                }

                if (!ui->comboBox_6->currentText().isEmpty())
                    cs->deleteConnectionLine(selectedItem, targetItem, scene);

                cs->connectComponents(selectedItem, targetItem, scene, thickness);
                update();
            });

}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{

    qDebug()<<"点击";
    // 获取鼠标点击的位置
    QPoint pos = event->pos();
    // 转换为场景坐标
    QPointF scenePos = scene->views().at(0)->mapToScene(pos);  // 通过视图转换为场景坐标

    // 遍历场景中的所有项
    for (QGraphicsItem *item : scene->items()) {
        if (item->boundingRect().contains(item->mapFromScene(scenePos))) {
            // 如果鼠标点击的位置在当前组件的矩形区域内

            if (auto powerSourceItem = dynamic_cast<PowerSourceItem*>(item)) {
                // 如果点击的是 PowerSourceItem
                qDebug() << "PowerSourceItem clicked";
            }
            else if (auto lightBulbItem = dynamic_cast<LightBulbItem*>(item)) {
                // 如果点击的是 LightBulbItem
                qDebug() << "LightBulbItem clicked";
            }
            else if (auto switchItem = dynamic_cast<SwitchItem*>(item)) {
                // 如果点击的是 SwitchItem
                qDebug() << "SwitchItem clicked";
            }
            break;  // 找到一个符合条件的组件后，跳出循环
        }
    }


    // 根据选择的元件类型设置拖拽状态
    if (PowerSource->geometry().contains(pos)) {
        draggingItemType = "PowerSource";  // 电源元件
    }
    else if (LightBulb->geometry().contains(pos)) {
        draggingItemType = "LightBulb";  // 灯泡元件
    }
    else if (Switch->geometry().contains(pos)) {
        draggingItemType = "Switch";  // 开关元件
    }

    // 更新界面，准备绘制图标
    update();
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (!draggingItemType.isEmpty()) {
        // 更新当前鼠标位置
        releasePos = event->pos(); // releasePos 是 QPoint 类型

        // 检查鼠标是否位于视图区域内
        QRect rect = ui->graphicsView->viewport()->rect();  // 使用 viewport() 获取视图显示区域
       if (rect.contains(releasePos.toPoint())) { // releasePos 是 QPoint 类型，直接传入
            // 视图内才进行绘制
            update();  // 触发视图重绘
        }
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (!draggingItemType.isEmpty()) {

        // 创建相应的图形元件
        QGraphicsItem *newItem = nullptr;
        if (draggingItemType == "PowerSource") {
            newItem = new PowerSourceItem();
        } else if (draggingItemType == "Switch") {
            newItem = new SwitchItem();
        } else if (draggingItemType == "LightBulb") {
            newItem = new LightBulbItem();
        }

        if (newItem) {

            // 使用 mapToScene 来获取场景坐标
            QPointF scenePos = ui->graphicsView->mapToScene(QPoint(releasePos.toPoint())); // Convert QPointF to QPoint
            newItem->setPos(scenePos.x() - 50, scenePos.y() - 40);
            //scene->addItem(newItem);  // 将新元件添加到场景中
            cs->addComponent(newItem);
        }

        // 重置拖拽状态
        draggingItemType.clear();
        releasePos = QPoint(-1, -1);  // 重置拖拽位置
        update();  // 更新视图以清除临时绘制
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    // 如果有正在拖拽的元件，绘制对应的图标
    if (!draggingItemType.isEmpty()) {
        // 检查鼠标是否在视图区域内
        QRect rect = ui->graphicsView->viewport()->rect();  // 使用 viewport() 获取视图显示区域
       if (rect.contains(releasePos.toPoint())) {  // releasePos 是 QPoint 类型，直接传入

            if (rect.contains(releasePos.toPoint())) {  // 将 QPointF 转换为 QPoint
                if (draggingItemType == "PowerSource") {
                    painter.drawPixmap(releasePos.toPoint(), PowerSource->grab());  // 确保传入的是 QPoint
                } else if (draggingItemType == "LightBulb") {
                    painter.drawPixmap(releasePos.toPoint(), LightBulb->grab());  // 确保传入的是 QPoint
                } else if (draggingItemType == "Switch") {
                    painter.drawPixmap(releasePos.toPoint(), Switch->grab());  // 确保传入的是 QPoint
                }
            }
        }
    }
}

